import unittest
from unittest.mock import Mock, patch, call


class TestUserService(unittest.TestCase):
    def test_normal_delete(self):
        user_mapper = Mock()
        product_mapper = Mock()
        logger = Mock()

        # 模拟方法调用
        user_mapper.delete_by_id.return_value = 1  # 影响1行
        product_mapper.delete_by_creator_id.return_value = 3  # 删除3个产品

        # 模拟被测试的函数
        def delete_user_by_id(user_id):
            user_mapper.delete_by_id(user_id)
            product_mapper.delete_by_creator_id(user_id)
            logger.info("删除用户成功")

        # 执行测试
        delete_user_by_id(1)

        # 验证调用
        user_mapper.delete_by_id.assert_called_once_with(1)
        product_mapper.delete_by_creator_id.assert_called_once_with(1)
        logger.info.assert_called_once_with("删除用户成功")

    def test_rollback_on_exception(self):
        user_mapper = Mock()
        product_mapper = Mock()

        # 模拟产品删除时抛出异常
        product_mapper.delete_by_creator_id.side_effect = RuntimeError("数据库连接失败")

        # 模拟被测试的函数（带事务处理）
        def delete_user_by_id(user_id):
            try:
                user_mapper.delete_by_id(user_id)
                product_mapper.delete_by_creator_id(user_id)
            except Exception as e:
                # 模拟事务回滚（实际需依赖数据库连接）
                raise e

        # 执行测试
        with self.assertRaises(RuntimeError) as cm:
            delete_user_by_id(1)

        # 验证异常信息
        self.assertEqual(str(cm.exception), "数据库连接失败")

        # 验证用户删除操作被调用（但因异常可能回滚）
        user_mapper.delete_by_id.assert_called_once_with(1)
        product_mapper.delete_by_creator_id.assert_called_once_with(1)

    def test_non_existent_user(self):
        user_mapper = Mock()
        product_mapper = Mock()
        logger = Mock()

        # 模拟删除不存在的用户（影响0行）
        user_mapper.delete_by_id.return_value = 0
        product_mapper.delete_by_creator_id.return_value = 0

        # 模拟被测试的函数
        def delete_user_by_id(user_id):
            user_mapper.delete_by_id(user_id)
            product_mapper.delete_by_creator_id(user_id)
            logger.info("删除用户成功")

        # 执行测试
        delete_user_by_id(999)

        # 验证调用
        user_mapper.delete_by_id.assert_called_once_with(999)
        product_mapper.delete_by_creator_id.assert_called_once_with(999)
        logger.info.assert_called_once_with("删除用户成功")


if __name__ == '__main__':
    unittest.main()